# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/8/12
library(optparse)
library(magrittr)
library(impute)
library(tidyverse)
library(NormalizeMets)
library(FitAR)

option_list <- list(
  make_option("--cc", default = "calculate_config.json", type = "character", help = "config file"),
  make_option("--si", default = "1;0", type = "character", help = "step "),
  make_option("--g", default = "group.txt", type = "character", help = "sample group file")
)
opt <- parse_args(OptionParser(option_list = option_list))

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/base.R"))

configJson <- fromJSON(opt$cc)

si <- opt$si %>%
  str_split(";") %>%
  unlist()
step <- si[1] %>%
  as.numeric()

extraColumn  <- configJson$datas$extraColumn[step]
rateStr  <- configJson$datas$extraMultiple[step]
rateStr

data <- read_tsv(str_c(step - 1, ".result.txt")) %>%
  rename(Metabolite = 1)

rate <- if (rateStr == "mean") {
  data %>%
    select_at(vars(!starts_with("QC"), -"Metabolite")) %>%
    summarise_all(function(x) {
      sum(x, na.rm = T)
    }) %>%
    mutate(mean = rowMeans(.)) %>%
    .$mean
}else {
  rateStr %>%
    as.numeric()
}

sampleIds <- data %>%
  select(-"Metabolite") %>%
  colnames() %>%
  factor(., levels = unique(.))

sampleIds

sampleInfo <- read_tsv(opt$g) %>%
  rename(SampleID = Sample) %>%
  mutate(SampleID = factor(SampleID, levels = sampleIds)) %>%
  arrange(SampleID)

sampleInfo

outData <- data %>%
  mutate(Metabolite = factor(Metabolite, levels = unique(Metabolite))) %>%
  gather("SampleID", "Value", -Metabolite, factor_key = T) %>%
  spread(Metabolite, "Value") %>%
  mutate_at(vars(-c("SampleID")), function(x) {
    div <- sampleInfo[, extraColumn] %>%
      unlist()
    (x * rate) / div
  }) %>%
  gather("Metabolite", "Value", -SampleID, factor_key = T) %>%
  spread(SampleID, "Value")

outData

write_tsv(outData, str_c(step, ".result.txt"))
write_csv(outData, str_c(step, ".extra_normal.csv"))








